/**
 * Created by ding on 2017/9/22.
 */
/**
 * Created by ding on 2017/9/20.
 */
var talkMainDT;
var dealMainDT;
var orgSelect = "";
var orgTableSelect = "";
var date = new Date;
var year = date.getFullYear();
/*曲线图表*/
var areaChartOptions = {
    //Boolean - If we should show the scale at all
    showScale: true,
    //Boolean - Whether grid lines are shown across the chart
    scaleShowGridLines: true,
    //String - Colour of the grid lines
    scaleGridLineColor: "rgba(0,0,0,.05)",
    //Number - Width of the grid lines
    scaleGridLineWidth: 1,
    //Boolean - Whether to show horizontal lines (except X axis)
    scaleShowHorizontalLines: true,
    //Boolean - Whether to show vertical lines (except Y axis)
    scaleShowVerticalLines: true,
    //Boolean - Whether the line is curved between points
    bezierCurve: true,
    //Number - Tension of the bezier curve between points
    bezierCurveTension: 0.3,
    //Boolean - Whether to show a dot for each point
    pointDot: true,
    //Number - Radius of each point dot in pixels
    pointDotRadius: 4,
    //Number - Pixel width of point dot stroke
    pointDotStrokeWidth: 1,
    //Number - amount extra to add to the radius to cater for hit detection outside the drawn point
    pointHitDetectionRadius: 20,
    //Boolean - Whether to show a stroke for datasets
    datasetStroke: true,
    //Number - Pixel width of dataset stroke
    datasetStrokeWidth: 2,
    //Boolean - Whether to fill the dataset with a color
    datasetFill: true,
    //String - A legend template
    legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].lineColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>",
    //Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
    maintainAspectRatio: true,
    //Boolean - whether to make the chart responsive to window resizing
    responsive: true
};
var lineChartOptions = areaChartOptions;
lineChartOptions.datasetFill = false;
var arryTalk = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var arryDeal = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var arrySpend = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
/*........*/
//绘制曲线
$.getlineChart = function () {
    $.ajax({
        url: '../rds_highLever_fault_count/getDealReportExpensesCount',
        type: 'post',
        data: {
            year: year,
            orgId: $("#orgChoose").val(),
            userId: gUserLoginResult.userId
        },
        dataType: 'json',
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                var timeJson = msg.jsonData;
                arryTalk = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
                arryDeal = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
                arrySpend = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
                var talkCount = 0;
                var dealCount = 0;
                var spendCount = 0;
                for (var i = 0; i < timeJson.length; i++) {
                    var time = timeJson[i].time;
                    var timearr = time.replace(" ", ":").replace(/\:/g, "-").split("-");
                    var month = timearr[1];
                    if (timeJson[i].type == 1) {
                        arryDeal[month - 1]++;
                        dealCount++;
                    }
                    else if (timeJson[i].type == 0) {
                        arryTalk[month - 1]++;
                        talkCount++;
                    }
                    else if (timeJson[i].type == 2) {
                        arrySpend[month - 1] += timeJson[i].spendMoney / 1000;
                        spendCount += timeJson[i].spendMoney;
                    }
                }

                $("#linCountOutPut").html("年故障统计线性表(<span style='color: #CD3700'>申报:</span>" + talkCount + " <span style='color:#4EEE94 '>处理:</span>" + dealCount + " <span style='color:rgba(0, 29, 255, 0.84); '>报修金额:</span>" + spendCount.toFixed(2) + "元)");
                $('#lineChart').remove();
                $('#lineChartParent').html("<canvas id='lineChart' style='height:250px'></canvas>");
                var lineChartCanvas = $("#lineChart").get(0).getContext("2d");
                var lineChart = new Chart(lineChartCanvas);
                var areaChartData = {
                    labels: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
                    datasets: [
                        {
                            label: "申报数",
                            fillColor: "#CD3700",
                            strokeColor: "#CD3700",
                            pointColor: "#CD3700",
                            pointStrokeColor: "#c1c7d1",
                            pointHighlightFill: "#fff",
                            pointHighlightStroke: "rgba(220,220,220,1)",
                            data: arryTalk
                        },
                        {
                            label: "处理数",
                            fillColor: "#4EEE94",
                            strokeColor: "#4EEE94",
                            pointColor: "#4EEE94",
                            pointStrokeColor: "rgba(60,141,188,1)",
                            pointHighlightFill: "#fff",
                            pointHighlightStroke: "rgba(60,141,188,1)",
                            data: arryDeal
                        },
                        {
                            label: "报修金额（K）",
                            fillColor: "rgba(0, 29, 255, 0.84)",
                            strokeColor: "rgba(0, 29, 255, 0.84)",
                            pointColor: "rgba(0, 29, 255, 0.84)",
                            pointStrokeColor: "rgba(0, 29, 255, 0.84)",
                            pointHighlightFill: "#fff",
                            pointHighlightStroke: "rgba(0, 29, 255, 0.84)",
                            data: arrySpend
                        }
                    ]
                };
                lineChart.Line(areaChartData, lineChartOptions);
            }
        }
    })
};

//按维护单位查询的下拉框
$.getDealOrg = function () {
    $.ajax({
        url: '../rds_count/getDealOrg',
        type: 'post',
        data: {
            userId: gUserLoginResult.userId,
            orgId: gUserLoginResult.orgId
        },
        dataType: 'json',
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    orgSelect = "<div class='input-group input-group-sm'><select class='form-control' id='orgChoose' onchange='$.getlineChart()'> ";
                    orgTableSelect = "<div class='input-group input-group-sm'><select class='form-control' id='orgTableChoose'> "
                    if (msg.jsonData.length > 1) {
                        orgSelect += "<option value='-1'>维护公司</option>";
                        orgTableSelect += "<option value='-1'>维护公司</option>";
                    }
                    if (msg.jsonData.length == 0) {
                        orgSelect += "<option value='-1'>无权限</option>";
                        orgTableSelect += "<option value='-1'>无权限</option>";
                    }
                    for (var i = 0; i < msg.jsonData.length; i++) {
                        orgSelect += "<option value='" + msg.jsonData[i].orgId + "'>" + msg.jsonData[i].orgName + "</option>";
                        orgTableSelect += "<option value='" + msg.jsonData[i].orgId + "'>" + msg.jsonData[i].orgName + "</option>";
                    }
                    orgSelect += "</select></div>";
                    orgTableSelect += "</select></div>";
                    $("#orgSelect").html(orgSelect);
                    $.getlineChart();
                    if (gUserLoginResult.orgType == 0 && msg.jsonData.length == 1) {
                        $("#orgChoose").hide();
                        orgTableSelect = "<select class='form-control' id='orgTableChoose' style='display: none'><option value='-1'>维护公司</option></select>"
                    }
                }
            }
        }
    })
};

$(function () {
    $.getDealOrg();
    talkMainDT = $("#talk_mainDataTables").DataTable({
        ajax: {
            url: "../rds_highLever_fault_count/getFault4DT",
            type: "POST",
            data: function (d) {
                d.userId = gUserLoginResult.userId;
                d.orgId = gUserLoginResult.orgId;
                d.search = $('#talk_mainDataTables').DataTable().search(this.value);
            }
        },
        columns: [{
            data: "highLeverFaultId"
        }, {
            data: "highLeverFaultPhoto",
            render: function (data, type, row) {
                var img = "../../images/default_photo.png";
                if (data != null) {
                    if (data.length != 0) {
                        img = data;
                    }
                }
                return "<img src='" + img + "' style='width:50px;height:40px;cursor: pointer' " +
                    "onclick='$.showPicModal(\"" + img + "\")'> ";
            }
        }, {
            data: "highLeverPhoto",
            render: function (data, type, row) {
                var img = "../../images/default_photo.png";
                if (data != null) {
                    if (data.length != 0) {
                        img = data;
                    }
                }
                return "<img src='" + img + "' style='width:50px;height:40px;cursor: pointer' " +
                    "onclick='$.showPicModal(\"" + img + "\")'> ";
            }
        }, {
            data: "highLeverFaultLevel",
            render: function (data, type, row) {
                return "<button class='btn btn-default btn-xs btn-flat'>" + data + "</button>";
            }
        }, {
            data: "highLeverCheck",
            render: function (data, type, row) {
                //企业负责人审核(通过为1,不通过-1，未审核0)
                if (data == 0) {
                    return "<button class='btn btn-default btn-xs btn-flat'>未审核</button>";
                }
                else if (data == 1) {
                    return "<button class='btn btn-success btn-xs btn-flat'>通过</button>";
                }
                else {
                    return "<button class='btn btn-danger btn-xs btn-flat'>不通过</button>";
                }
            }
        }, {
            data: "highLeverMainCheck",
            render: function (data, type, row) {
                //主管单位审核(通过为1,不通过-1，未审核0)
                if (data == 0) {
                    return "<button class='btn btn-default btn-xs btn-flat'>未审核</button>";
                }
                else if (data == 1) {
                    return "<button class='btn btn-success btn-xs btn-flat'>通过</button>";
                }
                else {
                    return "<button class='btn btn-danger btn-xs btn-flat'>不通过</button>";
                }
            }
        }, {
            data: "highLeverFaultTime",
            render: function (data, type, row) {
                if (data == null)
                    return "暂无";
                return data.substring(0, 10);
            }
        }, {
            data: "highLeverCheckTime",
            render: function (data, type, row) {
                if (data == null)
                    return "暂无";
                return data.substring(0, 10);
            }
        }, {
            data: "highLeverOrgName"
        }, {
            data: "highLeverId",
            render: function (data, type, row) {
                nowRoadPoleId = data;
                return "<button class='btn btn-primary btn-xs btn-flat' onclick='$.getAllInformation(" + JSON.stringify(row) + ")' title='预览'>" +
                    "<i class='glyphicon glyphicon-eye-open'></i></button>";
            }
        }],
        dom: "<'row'<'col-md-4'l><'#tmainToolbar.col-md-8'>r>t<'row'<'col-md-6'i><'col-md-6'p>>",
        initComplete: function () {
            // 下拉工具栏按钮的权限
            $("#tmainToolbar").empty();
            var strToolBar = "<div class='pull-right'><div class='btn-group'><button type='button' class='btn btn-primary btn-sm btn-flat'><i class='fa fa-cog'></i> 操作</button>";
            strToolBar += "<button type='button' class='btn btn-primary btn-sm btn-flat dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false' onclick='$.dateReturn()'>";
            strToolBar += "<span class='caret'></span><span class='sr-only'>切换下拉</span></button><ul class='dropdown-menu'>";
            strToolBar += "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' onclick='$.refreshDatables();'><i class='fa fa-refresh'></i> 刷新</button></li>";
            strToolBar += "</ul></div>&nbsp;" + orgTableSelect + "&nbsp;<div class='input-group input-group-sm'><input type='text' class='form-control' style='width: 170px;' name='searchText' id='timeLimit' placeholder='报告/维护时间' readonly='readonly'>";
            strToolBar += "<span class='input-group-btn'><button class='btn btn-primary btn-flat' type='button' onclick='$(this).searchDT()'><i class='fa fa-search'></i></button></span></div></div>";
            $("#tmainToolbar").append(strToolBar);
            //让时间插件正常使用
            $("#timeLimit").focus(function () {
                $('#timeLimit').daterangepicker({
                    autoUpdateInput: false,
                    locale: {
                        format: 'YYYY-MM-DD',
                        applyLabel: '确认',
                        cancelLabel: '取消',
                        fromLabel: '从',
                        toLabel: '到',
                        weekLabel: 'W',
                        customRangeLabel: 'Custom Range',
                        daysOfWeek: ["日", "一", "二", "三", "四", "五", "六"],
                        monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
                    }
                }).on('cancel.daterangepicker', function (ev, picker) {
                    $(this).val('');
                }).on('apply.daterangepicker', function (ev, picker) {
                    $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
                });
                $(".dropdown-menu").css("min-width", "0");
            });
        },
        processing: true,
        serverSide: true,
        ordering: false,
        select: false,
        autoFill: true,
        displayLength: 5,
        lengthMenu: [[5, 10, 15, 20, 50, 100, 150, -1], [5, 10, 15, 20, 50, 100, 150, "All"]],
        language: {
            url: "zh_cn.json"
        },
        fnDrawCallback: function () {// 序号自增回调函数
            var api = this.api();
            var startIndex = api.context[0]._iDisplayStart;
            api.column(0).nodes().each(function (cell, i) {
                cell.innerHTML = startIndex + i + 1;
            });
        }
    });
    dealMainDT = $("#deal_mainDataTables").DataTable({
        ajax: {
            url: "../rds_highLever_fault_count/getDevice4DT",
            type: "POST",
            data: function (d) {
                d.userId = gUserLoginResult.userId;
                d.orgId = gUserLoginResult.orgId;
                d.search = $('#deal_mainDataTables').DataTable().search(this.value);
            }
        },
        columns: [{
            data: "highLeverFaultId"
        }, {
            data: "highLeverPhoto",
            render: function (data, type, row) {
                var img = "../../images/default_photo.png";
                if (data != null) {
                    if (data.length != 0) {
                        img = data;
                    }
                }
                return "<img src='" + img + "' style='width:50px;height:40px;cursor: pointer' " +
                    "onclick='$.showPicModal(\"" + img + "\")'> ";
            }
        }, {
            data: "highLeverFaultPhoto",
            render: function (data, type, row) {
                var img = "../../images/default_photo.png";
                if (data != null) {
                    if (data.length != 0) {
                        img = data;
                    }
                }
                return "<img src='" + img + "' style='width:50px;height:40px;cursor: pointer' " +
                    "onclick='$.showPicModal(\"" + img + "\")'> ";
            }
        }, {
            data: "highLeverMaintenancePhoto",
            render: function (data, type, row) {
                var img = "../../images/default_photo.png";
                if (data != null) {
                    if (data.length != 0) {
                        img = data;
                    }
                }
                return "<img src='" + img + "' style='width:50px;height:40px;cursor: pointer' " +
                    "onclick='$.showPicModal(\"" + img + "\")'> ";
            }
        }, {
            data: "highLeverMoney",
            render: function (data, type, row) {
                return data + "元";
            }
        }, {
            data: "highLeverMaintenanceTime"
        }, {
            data: "highLeverOrgName"
        }, {
            data: "highLeverFaultId",
            render: function (data, type, row) {
                nowRoadPoleId = data;
                return "<button class='btn btn-primary btn-xs btn-flat' onclick='$.getAllInformation(" + JSON.stringify(row) + ")' title='预览'>" +
                    "<i class='glyphicon glyphicon-eye-open'></i></button>";
            }
        }],
        dom: "<'row'<'col-md-4'l><'#tmainToolbar.col-md-8'>r>t<'row'<'col-md-6'i><'col-md-6'p>>",
        initComplete: function () {
            // 下拉工具栏按钮的权限
            $("#dmainToolbar").empty();
        },
        processing: true,
        serverSide: true,
        ordering: false,
        select: false,
        autoFill: true,
        displayLength: 5,
        lengthMenu: [[5, 10, 15, 20, 50, 100, 150, -1], [5, 10, 15, 20, 50, 100, 150, "All"]],
        language: {
            url: "zh_cn.json"
        },
        fnDrawCallback: function () {// 序号自增回调函数
            var api = this.api();
            var startIndex = api.context[0]._iDisplayStart;
            api.column(0).nodes().each(function (cell, i) {
                cell.innerHTML = startIndex + i + 1;
            });
        }
    });
});
// 搜索框查询操作
$.fn.searchDT = function () {
    var searchText = $("input[name='searchText']").val();
    if (searchText == "") {
        searchText = -1;
    }
    var orgTableName = $("#orgTableChoose").val();
    var searchContext = searchText + "#" + orgTableName;
    dealMainDT.search(searchContext).draw();
    talkMainDT.search(searchContext).draw();
};


//使时间插件使用正常
$.dateReturn = function () {
    $(".dropdown-menu").css("min-width", "100%");
};

$.refreshDatables = function () {
    talkMainDT.ajax.reload(null, false);
    dealMainDT.ajax.reload(null, false);
};


//Date picker
$('#datepicker').datepicker({
    language: "zh-CN",
    format: 'yyyy',
    autoclose: true,
    startView: 'years',
    maxViewMode: 'years',
    minViewMode: 'years',
}).on('hide', function (e) {
    year = $("#datepicker").val();
    $.getlineChart();
});
//设置默认时间
$('#datepicker').datepicker('setDate', new Date());
$('#datepicker').datepicker('setEndDate', '2100');
$('#datepicker').datepicker('setStartDate', '2000');


//标杆标牌详细信息
$.getAllInformation = function (jsonData) {
    $("#myDiv").empty();
    $("#address").html(jsonData.highLeverProvince + " " + jsonData.highLeverCity + " " + jsonData.highLeverArea + " " + jsonData.highLeverRoadName + " " + jsonData.highLeverStartRoad + "起 " + jsonData.highLeverEndRoad + "止");
    // 形状 0:长方形; 1:圆形
    var temp;
    if (jsonData.highLeverShape == 0)
        temp = "长方形";
    if (jsonData.highLeverShape == 1)
        temp = "圆形";
    $("#solarEnergyType").html(temp);
    // 材质 0:树脂; 1:水泥; 2:球墨; 3:其他
    if (jsonData.highLeverMaterial == 0)
        temp = "树脂";
    if (jsonData.highLeverMaterial == 1)
        temp = "水泥";
    if (jsonData.highLeverMaterial == 2)
        temp = "球墨";
    if (jsonData.highLeverMaterial == 3)
        temp = "其他";
    $("#solarEnergyMaterial").html(temp);


    $("#solarEnergyStyle").html(jsonData.highLeverSize);

    $("#create").html(jsonData.highLeverFaultCreatorName);
    $("#solarEnergyPeriod").html(jsonData.highLeverPeriod + "年");
    $("#company").html(jsonData.highLeverOrgName);
    $("#mainOrg").html(jsonData.highLeverMainOrgName);


    $("#img").attr("src", jsonData.highLeverFaultPhoto);

    $("#img").click(function () {
        $.showPicModal($(this).attr("src"));
    });

    $("#modal-AllInformation").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
};